<script setup lang="ts">
import type { PropType } from 'vue'
import { computed } from 'vue'
import { IconCheckCircleFill, IconExclamationCircleFill } from '@arco-design/web-vue/es/icon'
import { isUndefined } from '@/utils/typed'

defineOptions({ name: 'ValidateRadioGroup' })

const $props = defineProps({
  modelValue: {
    type: [String, Number, Boolean] as PropType<string | number | boolean>,
    default: undefined,
  },
  validator: {
    type: Function as PropType<() => boolean>,
    default: undefined,
  },
})
const $emits = defineEmits(['update:modelValue', 'input', 'change'])

const computedValue = computed<string | number | boolean | undefined>({
  get: () => $props.modelValue,
  set: (newValue) => {
    $emits('update:modelValue', newValue)
    $emits('input', newValue)
    $emits('change', newValue)
  },
})

const computedValidateState = computed<boolean>(() => {
  if ($props.validator && typeof $props.validator === 'function') {
    return $props.validator()
  }
  if (typeof $props.modelValue === 'string') {
    return !!$props.modelValue.length
  }
  return !isUndefined(computedValue.value)
})
</script>

<template>
  <a-radio-group
    v-model="computedValue"
    type="button"
    size="mini"
    :class="computedValidateState ? 'feedback-success' : 'feedback-error'"
  >
    <slot />
    <a-radio value="__validate_flag" disabled>
      <IconCheckCircleFill v-if="computedValidateState" size="16" />
      <IconExclamationCircleFill v-else size="16" />
    </a-radio>
  </a-radio-group>
</template>

<style lang="scss">
  .arco-radio-group-button.feedback-success .arco-icon {
    color: rgb(var(--success-6));
  }
  .arco-radio-group-button.feedback-error .arco-icon {
    color: rgb(var(--warning-6));
  }
</style>
